Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath({'Ext.ux' : 'extjs4/ux'});
Ext.require([
             'Ext.grid.*',
             'Ext.data.*',
             'Ext.ux.grid.FiltersFeature',
             'Ext.ux.ajax.JsonSimlet',
             'Ext.ux.ajax.SimManager'
]);
Ext.define('TS.controller.RpRecBillEditors',{
	extend: 'Ext.app.Controller',
	models:['rp.RpBillModel','rp.RpBillDetailModel','rp.ArpBillModel'],
	views:['rp.RpRecBillEditor','rp.RpARecBillSettleSelector'],
	init:function(){
		this.control({
			'rprecbilleditor button[action=saveBill]':{click:this.onSaveBill},
			'rprecbilleditor button[action=archiveBill]':{click:this.onArchiveBill},
			'rprecbilleditor button[action=unArchiveBill]':{click:this.onUnArchiveBill},
			'rprecbilleditor button[action=autoCheckBill]':{click:this.onAutoCheckBill},
			'rprecbilleditor button[action=printBill]':{},
			'rprecbilleditor button[action=refARecBill]':{click:this.selectARecBill}
		})
	},
	//保存单据
	onSaveBill:function(button) {
		var me = this;
		var form = button.up('form');
		var pass = form.isValid();
		if(!pass) {
			Ext.Msg.show({
				title:'警告',
				msg:'数据验证不通过，请检查！',
				buttons:Ext.Msg.OK,
				icon:Ext.Msg.WARNING
			});
			return;
		}
		form.getForm().updateRecord();
		var record = form.getRecord();
		if(form.down('numberfield[name=discount]').getValue() == 0) {
			record.set('discount',0);
		}
		var data = record.getData(true);
		Ext.Ajax.request({
			url:'rp/recbill/save.do',
			method:'POST',
			jsonData:data,
			success:function(response) {
		    	var data=Ext.decode(response.responseText);
		    	if(data.success==true){
		    		//如果是新建单据保存，需要更新单据主体ID与单据明细中的ID
		    		var model = form.getRecord();
		    		if(model.get('rpBillId') != data.o.rpBillId) {
			    		model.set('rpBillId',data.o.rpBillId);
			    		if(model.details() && model.details().count() > 0) {
			    			var store = model.details();
			    			store.each(function(record) {
			    				record.set('rpBillId',data.o.rpBillId);
			    			});
			    			store.commitChanges();
			    		}
		    		}
		    		if(data.o.archived && data.o.details.length > 0) {
		    			//单据保存并归档成功,询问是否自动核销
		    			model.set('archived',true);
		    			Ext.Msg.show({
		    				title:'询问',
		    				msg:'单据已保存并归档,是否自动核销?',
		    				buttons:Ext.Msg.YESNO,
		    				icon:Ext.Msg.QUESTION,
		    				fn:function(button) {
		    					if(button=='yes') {
		    						me.autoCheckBill(form,model);
		    						return;
		    					}
		    				}
		    			});
		    		} else {
			    		Ext.MessageBox.show({
			    			title:'ThinkGsp',
			    			msg:data.msg,
			    			buttons:Ext.Msg.OK,
			    			icon:Ext.Msg.INFO
			    		});	
		    		}
		    		form.onUpdateState(form,model);
		    	} else {
		    		Ext.MessageBox.show({
		    			title:'ThinkGsp',
		    			msg:data.msg,
		    			buttons:Ext.Msg.OK,
		    			icon:Ext.Msg.ERROR
		    		});			    		
		    	}
			}
		});
	},  
	//单据归档
    onArchiveBill:function(button) {
	   	 var me = button.up('form');
	   	 var bill = button.up('form').getRecord();
	   	 if(bill.get('rpBillId') || bill.get('rpBillId') != 0) {
	   		 if(bill.get('archived')) {
	       		 Ext.Msg.show({
	        			title:'ThinkGsp',
	        			msg:'单据已经归档!',
	        			buttons:Ext.Msg.OK,
	        			icon:Ext.Msg.WARNING
	        		 });
	        		 return;
	   		 }
				 Ext.Ajax.request({
					url:'rp/recbill/archive.do',
					params:{billId:bill.get('rpBillId')},
					success:function(response,opts){
						var result = Ext.decode(response.responseText);
						if(result.success) {
							bill.set('archived',true);
							this.onUpdateState(button.up('form'),bill);
							Ext.Msg.show({
								title:'ThinkGsp',
								msg:'归档成功',
								buttons:Ext.Msg.OK,
								icon:Ext.Msg.INFO
							});
						} else {
							Ext.Msg.show({
								title:'错误',
								msg:'[' + bill.get('rpBillCode') + ']' + result.msg,
								buttons:Ext.Msg.OK,
								icon:Ext.Msg.ERROR
							});
						}
					},
					scope:me
				 });
	   	 } else {
	   		 Ext.Msg.show({
	   			title:'ThinkGsp',
	   			msg:'单据未保存, 不能归档!',
	   			buttons:Ext.Msg.OK,
	   			icon:Ext.Msg.WARNING
	   		 });
	   		 return;
	   	 }
    },
    //单据反归档
    onUnArchiveBill:function(button) {
	   	 me = button.up('form');
	   	 var bill = button.up('form').getRecord();
	   	 if(bill.get('rpBillId') || bill.get('rpBillId') != 0) {
	   		 if(!bill.get('archived')) {
	       		 Ext.Msg.show({
	        			title:'ThinkGsp',
	        			msg:'单据未归档,不允许反归档!',
	        			buttons:Ext.Msg.OK,
	        			icon:Ext.Msg.WARNING
	        		 });
	        		 return;
	   		 }
				 Ext.Ajax.request({
					url:'rp/recbill/unArchive.do',
					params:{billId:bill.get('rpBillId')},
					success:function(response,opts){
						var result = Ext.decode(response.responseText);
						if(result.success) {
							bill.set('archived',false);
							this.onUpdateState(button.up('form'),bill);
							Ext.Msg.show({
								title:'ThinkGsp',
								msg:'反归档成功!',
								buttons:Ext.Msg.OK,
								icon:Ext.Msg.INFO
							});
						} else {
							Ext.Msg.show({
								title:'错误',
								msg:'单据:[' + bill.get('rpBillCode') + ']' + result.msg,
								buttons:Ext.Msg.OK,
								icon:Ext.Msg.ERROR
							});
						}
					},
					scope:me
				 });
	   	 } else {
	   		 Ext.Msg.show({
	   			title:'ThinkGsp',
	   			msg:'单据未保存, 不能反归档!',
	   			buttons:Ext.Msg.OK,
	   			icon:Ext.Msg.WARNING
	   		 });
	   		 return;
	   	 }
    },
    //自动核销
    onAutoCheckBill:function(button) {
    	var bill = button.up('form').getRecord();
    	var form = button.up('form');
    	this.autoCheckBill(form,bill);
    },
    //单据自动核销
    autoCheckBill:function(form,bill) {
    	 var me = this;
    	 if(!bill.get('archived')) {
    		 Ext.Msg.show({
    			 title:'警告',
    			 msg:'单据未归档,不允许自动核销',
    			 buttons:Ext.Msg.OK,
    			 icon:Ext.Msg.WARNING
    		 });
    		 return;
    	 }
 		 Ext.Ajax.request({
			url:'rp/recbill/autoCheck.do',
			params:{billId:bill.get('rpBillId')},
			success:function(response,opts){
				var result = Ext.decode(response.responseText);
				if(result.success) {
					bill.set('checkStatus',1);
					form.onUpdateState(form,bill);
					Ext.Msg.show({
						title:'ThinkGsp',
						msg:'自动核销成功!',
						buttons:Ext.Msg.OK,
						icon:Ext.Msg.INFO,
						fn:function(button) {
							form.close();
						}
					});
				} else {
					Ext.Msg.show({
						title:'错误',
						msg:'单据:[' + bill.get('rpBillCode') + ']归档失败，原因:' + result.msg,
						buttons:Ext.Msg.OK,
						icon:Ext.Msg.ERROR
					});
				}
			},
			scope:this
 		 }); 
    },    
    //引用应收单
 	selectARecBill:function(button) {
		var form = button.up('form');
		var record = form.getRecord();
		if(!Ext.isDefined(record.customerHasOneInstance) || !record.getcustomer().get('customerId')) {
			Ext.Msg.show({
				title:'ThinkGsp',
				msg:'请先输入要结算的客户!',
				buttons:Ext.Msg.OK,
				icon:Ext.Msg.WARNING
			});
			return;
		}
		var win = Ext.create('TS.view.rp.RpARecBillSettleSelector',{
			custId:record.getcustomer().get('customerId'),
			custName:record.getcustomer().get('customerName')
		});
		win.on({
			selected:function(records) {
				var form = this;
				var grid = form.down('grid');
				var store = grid.getStore();
				Ext.each(records,function(record){
					var exists = store.findRecord('arpBillId',record.get('arpBillId'));
					if(exists == null) {
						var detail = Ext.create('TS.model.rp.RpBillDetailModel');
						detail.set('arpBillId',record.get('arpBillId'));
						detail.set('settleAmount',record.get('currentCheckAmount'));
						detail.set('discount',0);
						detail.setarpBill(record);
						var record = form.getRecord();
						detail.set('rpBillId',record.get('rpBillId'));
						store.add(detail);
					} else {
						Ext.Msg.show({
							title:'ThinkGSp',
							msg:'您选择的应收单[' + record.get('arpBillCode') + ']已经存在结算明细中，不能再次结算!',
							buttons:Ext.Msg.OK,
							icon:Ext.Msg.WARNING
						});
					}
				});
				store.commitChanges();
				grid.getView().refresh();
				form.onUpdateBillAmount(grid);
			},
			scope: form
		});
		win.show();
	}     
});